﻿using Swifter.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using ZR.Infrastructure.Helper;

namespace CKS.Core.Framework
{
    public static partial class Ext
    {
        public static void SetPropertyValue(this object obj, string propertyName, object value)
        {
            // 获取对象的类型
            Type type = obj.GetType();
            // 获取指定名称的属性信息
            PropertyInfo property = type.GetProperty(propertyName);
            if (property != null && property.CanWrite)
            {
                // 将值转换为属性的类型
                object convertedValue = Convert.ChangeType(value, property.PropertyType);
                // 设置属性值
                property.SetValue(obj, convertedValue);
            }
        }

        public static string ToJson(this object obj)
        {

            return JsonFormatter.SerializeObject(obj);
        }

        public static bool CatchAction(this System.Action action, string logTitle = "")
        {
            try
            {
                action();
                return true;
            }
            catch (Exception ex)
            {
                LogHelper.WriteError(ex,$"{logTitle} 异常");
                return false;
            }
        }
    }
}
